//
//  HTClassStatisticsVC.swift
//  QuitSmokingApp
//
//  Created by   on 2024/3/6.
//

import UIKit
import DGCharts

class HTClassStatisticsVC: HTClassViewController {
    lazy var var_titleLabel: UILabel = {
        let var_label = UILabel()
        var_label.text = HTClassTool.ht_obtainYearMonth()
        var_label.textColor = .white
        var_label.font = .systemFont(ofSize: 28, weight: .bold)
        return var_label
    }()
    lazy var var_date_select: UIButton = {
        let var_button = UIButton()
        var_button.onTap { [weak self] in
            HTClassYearMonthTool.ht_showDatePick {[weak self] var_date in
                self?.var_titleLabel.text = HTClassTool.ht_convertToFixedFormat(var_date)
                self?.var_current_date = HTClassTool.ht_convertToFixedFormat(var_date)
                self?.ht_calculationData(HTClassTool.ht_convertToFixedFormat(var_date))
            }
        }
        var_button.setImage(UIImage(named: "icon_date_select_icon"), for: .normal)
        return var_button
    }()
    lazy var var_history: UIButton = {
        let var_button = UIButton()
        var_button.onTap { [weak self] in
            self?.navigationController?.pushViewController(HTClassHistoryVC(), animated: true)
        }
        var_button.setImage(UIImage(named: "icon_history_icon"), for: .normal)
        return var_button
    }()
    /// 当前月平均每日吸烟数量
    lazy var var_avg_ciga: UILabel = {
        let var_label = UILabel()
        var_label.text = ""
        var_label.textColor = UIColor("#00FFF0")
        var_label.font = .systemFont(ofSize: 20, weight: .bold)
        return var_label
    }()
    /// 当前月平均每日焦油量
    lazy var var_avg_tar: UILabel = {
        let var_label = UILabel()
        var_label.text = ""
        var_label.textColor = UIColor("#00FFF0")
        var_label.font = .systemFont(ofSize: 20, weight: .bold)
        return var_label
    }()
    /// 当前月平均每日花费
    lazy var var_avg_expenditure: UILabel = {
        let var_label = UILabel()
        var_label.text = ""
        var_label.textColor = UIColor("#00FFF0")
        var_label.font = .systemFont(ofSize: 20, weight: .bold)
        return var_label
    }()
    
    lazy var var_top_bg_view: UIView = {
        let var_view = UIView()
        var_view.backgroundColor = UIColor("#212329")
        var_view.layer.cornerRadius = 8.auto()
        var_view.layer.borderWidth = 1
        var_view.layer.borderColor = UIColor("#298CB2").cgColor
        return var_view
    }()
    var var_current_date: String = HTClassTool.ht_obtainYearMonth()
    
    lazy var var_bottomView: UIView = {
        let var_view = UIView()
        var_view.layer.cornerRadius = 8.auto()
        var_view.layer.borderWidth = 1
        var_view.layer.borderColor = UIColor("#298CB2").cgColor
        var_view.layer.masksToBounds = true
        return var_view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
       
    }
    lazy var var_chartView: LineChartView = {
        let var_view = LineChartView()
        var_view.backgroundColor = .clear
        return var_view
    }()
    override func ht_setUI() {
        super.ht_setUI()
        self.view.addSubview(var_titleLabel)
        var_titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview().offset(-10.auto())
            make.top.equalToSuperview().offset(HTClassTool.STATIC_statusBarHeight + 20.auto())
        }
        self.view.addSubview(var_date_select)
        var_date_select.snp.makeConstraints { make in
            make.centerY.equalTo(var_titleLabel.snp.centerY)
            make.left.equalTo(var_titleLabel.snp.right).offset(6)
        }
        
        self.view.addSubview(var_history)
        var_history.snp.makeConstraints { make in
            make.centerY.equalTo(var_titleLabel.snp.centerY)
            make.right.equalToSuperview().offset(-15.auto())
        }
        
        self.view.addSubview(self.var_top_bg_view)
        var_top_bg_view.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(14.auto())
            make.right.equalToSuperview().offset(-14.auto())
            make.top.equalToSuperview().offset(HTClassTool.STATIC_navigationBarTotalHeight + 20.auto())
        }
        
        ht_topViewUI()
        ht_bottomViewUI()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
        ht_calculationData(var_current_date)
        ht_setData()
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: false)
    }
    
    func ht_topViewUI() {
        let var_ciga_title = ht_getTitleLabel(var_title: "AVG. NUMBER OF CIGARETTES/DAY")
        var_top_bg_view.addSubview(var_ciga_title)
        var_ciga_title.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20.auto())
            make.top.equalToSuperview().offset(20.auto())
        }
        var_top_bg_view.addSubview(self.var_avg_ciga)
        var_avg_ciga.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-35.auto())
            make.centerY.equalTo(var_ciga_title.snp.centerY)
        }
        let var_ciga_lin = ht_line()
        var_top_bg_view.addSubview(var_ciga_lin)
        var_ciga_lin.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20.auto())
            make.right.equalToSuperview().offset(-20.auto())
            make.top.equalTo(var_ciga_title.snp.bottom).offset(15.auto())
            make.height.equalTo(2)
        }
        
        //=============
        let var_tar_title = ht_getTitleLabel(var_title: "Avg. INTAKE OF TAR/DAY")
        var_top_bg_view.addSubview(var_tar_title)
        var_tar_title.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20.auto())
            make.top.equalTo(var_ciga_lin.snp.bottom).offset(15.auto())
        }
        
        var_top_bg_view.addSubview(self.var_avg_tar)
        var_avg_tar.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-35.auto())
            make.centerY.equalTo(var_tar_title.snp.centerY)
        }
        
        let var_avg_lin = ht_line()
        var_top_bg_view.addSubview(var_avg_lin)
        var_avg_lin.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20.auto())
            make.right.equalToSuperview().offset(-20.auto())
            make.top.equalTo(var_tar_title.snp.bottom).offset(15.auto())
            make.height.equalTo(2)
        }
        /// =======
        let var_expend_title = ht_getTitleLabel(var_title: "AVG.EXPENDITURE/DAY")
        var_top_bg_view.addSubview(var_expend_title)
        var_expend_title.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20.auto())
            make.top.equalTo(var_avg_lin.snp.bottom).offset(15.auto())
            make.height.equalTo(21)
            make.bottom.equalToSuperview().offset(-15.auto())
        }
        var_top_bg_view.addSubview(self.var_avg_expenditure)
        var_avg_expenditure.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-35.auto())
            make.centerY.equalTo(var_expend_title.snp.centerY)
        }
        
        
    }
    
    func ht_bottomViewUI() {
        self.view.addSubview(self.var_bottomView)
        var_bottomView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(14.auto())
            make.right.equalToSuperview().offset(-14.auto())
            make.top.equalTo(var_top_bg_view.snp.bottom).offset(20.auto())
            make.height.equalTo(325.auto())
        }
        var_bottomView.addSubview(var_chartView)
        var_chartView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        let var_left_lin = UILabel()
        var_left_lin.backgroundColor = .white
        var_bottomView.addSubview(var_left_lin)
        var_left_lin.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.bottom.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(10)
            make.width.equalTo(2)
        }
        let var_right_lin = UILabel()
        var_right_lin.backgroundColor = .white
        var_bottomView.addSubview(var_right_lin)
        var_right_lin.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.bottom.equalToSuperview().offset(-10)
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(2)
        }
        
//        var_chartView.delegate = self
        var_chartView.chartDescription.enabled = false
        var_chartView.dragEnabled = true
        var_chartView.setScaleEnabled(true)
        var_chartView.pinchZoomEnabled = true
        var_chartView.legend.form = .none
        
        var_chartView.xAxis.drawLabelsEnabled = false
        var_chartView.xAxis.drawAxisLineEnabled = false
        var_chartView.xAxis.drawGridLinesEnabled = false
//        var_chartView.drawBordersEnabled = true
        var_chartView.leftAxis.drawLabelsEnabled = false
        var_chartView.leftAxis.drawAxisLineEnabled = false
        var_chartView.leftAxis.drawGridLinesEnabled = false

        var_chartView.rightAxis.drawLabelsEnabled = false
        var_chartView.rightAxis.drawAxisLineEnabled = false
        var_chartView.rightAxis.drawGridLinesEnabled = false
        var_chartView.animate(xAxisDuration: 0.5, easingOption: .easeInOutBack)
        
        let var_des_label = UILabel()
        var_des_label.textColor = UIColor("#797673")
        var_des_label.numberOfLines = 0
        var_des_label.textAlignment = .center
        var_des_label.font = .systemFont(ofSize: 14)
        var_des_label.text = "The line chart only shows data for the past seven days."
        self.view.addSubview(var_des_label)
        var_des_label.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(14.auto())
            make.right.equalToSuperview().offset(-14.auto())
            make.top.equalTo(var_bottomView.snp.bottom).offset(10)
        }
    }
    func ht_setData() {
        let var_data_set = HTClassCalculationTool.ht_getRecentData()
        var var_values: [ChartDataEntry] = []
        for var_index in 0..<var_data_set.count {
            let var_model = var_data_set[var_index]
            let var_chart = ChartDataEntry(x: Double(var_index), y: Double(var_model.var_cigarettes_smoked_today) ?? 0.0, data: var_model)
            var_values.append(var_chart)
        }
        let var_set1 = LineChartDataSet(entries: var_values, label: "")
        var_set1.drawIconsEnabled = false
        ht_setup(var_set1)

        let var_value = ChartDataEntry(x: Double(3), y: 3)
        var_set1.addEntryOrdered(var_value)
        let gradientColors = [UIColor.clear.cgColor, UIColor("#56E3FA").cgColor, UIColor("#56E3FA").cgColor]
        let gradient = CGGradient(colorsSpace: nil, colors: gradientColors as CFArray, locations: nil)!
        var_set1.fillAlpha = 1
        var_set1.fill = LinearGradientFill(gradient: gradient, angle: 90)
        var_set1.drawFilledEnabled = true

        let data = LineChartData(dataSet: var_set1)

        var_chartView.data = data
    }

    private func ht_setup(_ var_dataSet: LineChartDataSet) {
        var_dataSet.valueTextColor = UIColor.clear
        var_dataSet.lineCapType = .butt
        var_dataSet.highlightLineDashLengths = [5,5]
        var_dataSet.setColor(UIColor("#56E3FA")) //折线颜色
        var_dataSet.setCircleColor(.clear)
        var_dataSet.gradientPositions = nil
        var_dataSet.lineWidth = 5
        var_dataSet.circleRadius = 3
        var_dataSet.drawCircleHoleEnabled = true
        var_dataSet.valueFont = .systemFont(ofSize: 9)
        var_dataSet.formLineDashLengths = [5, 2.5]
        var_dataSet.formLineWidth = 20
        var_dataSet.formSize = 5
        var_dataSet.drawValuesEnabled = false
    }
    func ht_line() -> UILabel {
        let var_lin = UILabel()
        var_lin.backgroundColor = UIColor("#4F4F4F")
        return var_lin
    }
    
    func ht_getTitleLabel(var_title:String) -> UILabel {
        let var_titleLabel = UILabel()
        var_titleLabel.text = var_title
        var_titleLabel.textColor = .white
        var_titleLabel.font = .systemFont(ofSize: 13, weight: .bold)
        return var_titleLabel
    }
    
    func ht_calculationData(_ date: String) {
        let var_all_data = HTClassCalculationTool.ht_getPlanDataValue(date)
        var var_count = 0 // 总数量
        var var_price_totla = 0.0 // 价格
        var var_tar_totla = 0.0 // 焦油
        for var_item in var_all_data {
            let var_number = Int(var_item.var_cigarettes_smoked_today) ?? 0
            var_count += var_number
            let var_price = Double(var_item.var_cigarettePrice) ?? 0.0
            var_price_totla += var_price * Double(var_count)
            
            let var_tar = Double(var_item.var_tarContentPerCigarette) ?? 0.0
            var_tar_totla += var_tar * Double(var_count)
        }
        if var_all_data.count == 0 {
            var_avg_ciga.text = ""
            var_avg_tar.text = ""
            var_avg_expenditure.text = ""
        } else {
            var_avg_ciga.text = String(format: "%d", var_count/var_all_data.count)
            var_avg_tar.text = String(format: "%.1f", var_tar_totla/Double(var_all_data.count))
            var_avg_expenditure.text = String(format: "%.1f", var_price_totla/Double(var_all_data.count))
        }
        
    }
}
